<template>
    <div id="container" class="text-white text-sm bg-primary-300 min-h-screen pt-12">
      <div class="text-center text-2xl p-8">重置密码</div>
      <div class="flex items-center justify-center">
        <div class="w-1/4 p-4 bg-gray-100 rounded-lg shadow-lg">
          <div class="text-black text-center p-4">
            <p class="font-bold py-4">请输入注册时的邮箱</p>
            <div>
              <input
                v-model="email"
                class="outline-0 h-9 rounded border border-green-600 placeholder-gray-400 w-64 px-2 py-1 max-w-[280px]"
                type="text"
                placeholder="邮箱地址"
              />
            </div>
          </div>
          <div class="flex justify-center">
            <button
              v-on:click="handleResetPassword"
              class="bg-green-500 text-white px-4 py-2 rounded"
            >
              发送邮件
            </button>
          </div>
        </div>
      </div>
    </div>
  </template>

<script setup>
import { ref } from 'vue';
import { resetPassword as apiResetPassword } from '@/api/account';
import { showToast } from '@/utils/toast';

const email = ref('');

async function handleResetPassword() {
  if (!email.value) {
    showToast('请输入邮箱地址', 'error');
    return;
  }

  try {
    const response = await apiResetPassword({ email: email.value });
    console.log(response);
    showToast('邮件已发送', 'success');
  } catch (error) {
    console.error('发送邮件失败:', error);
    if (error.response && error.response.data) {
      const errorData = error.response.data;
      let errorMessage = '发送邮件失败，请重试';

      if (errorData.email && Array.isArray(errorData.email)) {
        errorMessage = errorData.email.join(' ');
      } else if (errorData.detail) {
        errorMessage = errorData.detail;
      } else if (Array.isArray(errorData) && errorData.length > 0) {
        errorMessage = errorData.join(' ');
      }

      showToast(errorMessage, 'error');
    } else {
      showToast('发送邮件失败，请检查网络连接', 'error');
    }
  }
}


</script>